import globalData from './data.js'

export default function authRequest(params) {	
	let token = globalData.employee.tokenkey;
	let header = {
		'Content-Type': 'application/json',
		'Accept': 'application/json'
	};
	if (params.header) {
		header = Object.assign(header, params.header);
	}
	
	
	let paramsData = {}
	if(token){
		paramsData.token = token
		paramsData.operatorno = globalData.employee.employeeid
	}
	if(params.data){
		paramsData = Object.assign(paramsData,params.data)
	}
	
	//过滤掉没填的空属性
	if(params.filter){		
		Object.keys(paramsData).forEach(key=>{
			if(paramsData[key] === '' || !paramsData[key]) delete paramsData[key];
		})
	}

	return new Promise((resolve, rejected) => {
		wx.request({
			header: header,
			url: globalData.apiBaseUrl + params.url,
			method: params.method ? params.method : 'GET',
			data: paramsData,
			responseType: params.responseType ? params.responseType : 'text',
			success: function(res) {
				//res.data.errorcode = '100005' //模拟未注册							
				if (res.data.errorcode === 0) {								
					resolve(res.data)
				} else {
					console.log('333')
					if (res.data.errorcode == '100005') {
						if(!globalData.hasShowLogin){
							login().then(() => {
								authRequest(params).then(r => {
									resolve(r)
								})
							})
						}else{
							//允许用户不登录
							rejected(res)
						}
					}else{
						rejected(res)
					}
				}

			},
			fail: function(e) {
				rejected(e)
			}
		})
	});

}

export function login() {
	return new Promise((resolve, rejected) => {
		uni.login({
			success: res => {
				wx.request({
					url: globalData.apiBaseUrl + '/operator/login',
					method: 'GET',
					header: {
						'Content-Type': 'application/json',
						'Accept': 'application/json'
					},
					data: {
						loginname: res.code,
						pass: globalData.pass,
						accounttype: globalData.accounttype
					},
					success: (res) => {
						console.log(res,'登录的接口')
						//res.data.errorcode = 100005 //模拟未注册
						if (res.data.errorcode === 0) {
							globalData.hasLogin = true;
							globalData.employee = res.data.employee;
							if (res.data.rows instanceof Array) {
								globalData.actions = res.data.rows.map(item => {
									return item.actionid;
								})
							}
							resolve()
						}else{
							//如果没有进入过登录界面，就先去登录界面，去过一次可以访问其他界面
							if(!globalData.hasShowLogin){
								uni.navigateTo({
									url: '/pages/front/wxlogin',
									fail:(r)=>{
										console.log(r,'失败了吗')
									}
								})
							}												
							rejected()
						}
					}
				})

			}
		})


	})
}
